package com.admin.education.controllers.api;

import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessageWithData;
import com.admin.education.common.response.Result;
import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.dataTransferObject.ServicesExcuteResult;
import com.admin.education.dataTransferObject.user.LoginRequest;
import com.admin.education.dataTransferObject.user.Response.LoginResponse;
import com.admin.education.dataTransferObject.weChat.Response.WeChatLoginResponse;
import com.admin.education.dataTransferObject.wx.WXTransfer;
import com.admin.education.services.Interfaces.IUserService;
import com.admin.education.services.Interfaces.IWXService;
import com.admin.education.services.Interfaces.IWeChatService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.Callable;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/login")
public class UserController {
    private long ttl;
    @Autowired
    private IUserService userService;
    @Autowired
    private IWXService wxService;
    @Autowired
    private IWeChatService weChatService;

    public  UserController(){
        ttl = 60*60*120*300;
    }
    @PostMapping("")
    public Callable<IResponseMessage> Login(@RequestBody @Valid LoginRequest loginRequest){
        return  new Callable<IResponseMessage>() {
            @Override
            public IResponseMessage call() throws Exception {
                IResponseMessage responseMessage = null;
                ServicesExcuteResult<LoginResponse> result = userService.Login(loginRequest);
                if(result.isSuccess()){
                    long nowMillis = System.currentTimeMillis();
                    Date now = new Date(nowMillis);
                    JwtBuilder jwtBuilder= Jwts.builder()
                            .setHeaderParam("typ", "JWT")
                            .setSubject(loginRequest.getUsername())
                            .claim("userName", loginRequest.getUsername())
                            .claim("userId",result.getData().getUserId())
                            .setIssuedAt(new Date())
                            .setIssuer(loginRequest.getUsername())
                            .signWith(SignatureAlgorithm.HS256, "secretkey");
                    long expMillis = nowMillis + ttl;
                    Date exp = new Date(expMillis);
                    jwtBuilder.setExpiration(exp).setNotBefore(now);

                    responseMessage =new ResponseMessageWithData<String>(Result.Success,jwtBuilder.compact());
                }
                else{
                    throw new BadRequestException(result.getErrorMessage());
                }
                return responseMessage;
            }
        };
    }
    @PostMapping("WeChat")
    public Callable<IResponseMessage> Login(@RequestBody Map<String,String> parameters){
        return new Callable<IResponseMessage>() {
            @Override
            public IResponseMessage call() throws Exception {
                String authCode =    parameters.get("Auth_Code");
                WXTransfer wxTransfer = wxService.Authenticate(authCode);

                WeChatLoginResponse weChatLoginResponse= weChatService.LoginByWeChat(wxTransfer);

                if(!weChatLoginResponse.isSuccess()){
                    throw new BadRequestException(weChatLoginResponse.getErrorMessage());
                }

                IResponseMessage responseMessage = new ResponseMessageWithData<String>(Result.Success,wxTransfer.getOpenId());
                return responseMessage;
            }
        };
    }
}
